<template>
	<el-dialog v-model="isVisible" :title="row ? '编辑保障服务' : '新增保障服务'" width="600px" :before-close="handleClose">
		<el-form ref="formRef" class="good-service-form" :model="form" :rules="rules" label-width="100px" inline>
			<el-form-item label="服务名称" prop="name">
				<el-input v-model="form.name" :maxlength="30" />
			</el-form-item>
			<el-form-item label="内容描述" prop="description">
				<el-input v-model="form.description" />
			</el-form-item>
			<el-form-item label="服务排序" prop="order">
				<el-input-number
					@blur="
						() => {
							form.order = form.order || 0;
						}
					"
					class="num-left"
					:min="0"
					:max="999999999"
					:controls="false"
					v-model="form.order"
				/>
			</el-form-item>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="handleClose">取消</el-button>
				<el-button type="primary" v-debounce="submit">保存</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="tsx">
import { FormRules, ElMessage } from 'element-plus';
import { ref, reactive, watch } from 'vue';
import { fetchCreateService, fetchUpdateService } from '/@/api/goods';

const props = defineProps({
	// 列表内容
	visible: {
		type: Boolean,
		default: () => false,
	},
	row: {
		type: Object,
		default: () => null,
	},
});

const emit = defineEmits(['handleClose']);

const isVisible = ref(false);

const formRef = ref();
const form = ref<any>({
	order: 0,
});

//校验规则
const rules = reactive<FormRules<any>>({
	name: [{ required: true, trigger: 'blur', message: '服务名称不能为空' }],
	description: [{ required: true, trigger: 'blur', message: '服务描述不能为空' }],
});

watch(
	() => props.visible,
	(val) => {
		if (val && props.row) {
			form.value = { ...props.row };
		}
		isVisible.value = val;
	},
	{
		immediate: true,
	}
);

const submit = async () => {
	formRef.value.validate(async (valid: boolean) => {
		if (valid) {
			const res = props.row ? await fetchUpdateService(form.value) : await fetchCreateService(form.value);
			if (res.code == 200) {
				ElMessage.success(props.row ? '编辑保障服务成功' : '新增保障服务成功');
				handleClose(true);
			} else {
				ElMessage.error(res.msg);
			}
		}
	});
};

const handleClose = (success?: boolean) => {
	form.value = {
		order: 0,
	};
	formRef.value.resetFields();
	emit('handleClose', success === true);
};
</script>

<style lang="scss">
.good-service-form {
	.el-form-item {
		width: 90%;
		.el-input-number {
			width: 100%;
		}
	}
}
</style>
